#include "httputil.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QEventLoop>
#include <QTimer>
#include <QRegExp>
#include <QDebug>
#include <QHttpMultiPart>

HttpUtil::HttpUtil(QObject *parent) : QObject(parent)
{

}

QString HttpUtil::get(const QUrl url)
{
    qDebug() << url;
    QNetworkAccessManager net;
    QNetworkRequest request(url);
    QNetworkReply *reply = net.get(request);

    // 添加消息循环机制...
    QEventLoop eventloop;
    connect(reply, SIGNAL(finished()), &eventloop, SLOT(quit()));
    QTimer::singleShot(5000, &eventloop, &QEventLoop::quit);
    qDebug() << "timer started";
    eventloop.exec();
    qDebug() << "eventLoop executed";

    QByteArray array;
    if(reply->isFinished()){
        if(reply->error() == QNetworkReply::NoError){
            qDebug() << "success";
        }
        array.append(reply->readAll());
    }
    else{
        disconnect(reply, &QNetworkReply::finished, &eventloop, &QEventLoop::quit);
        reply->abort();
        qDebug() << "timeout";
    }
    reply->deleteLater();

    QString responose = QString::fromUtf8(array);
    // qDebug() << responose;
    return responose;
}

QString HttpUtil::post(const QUrl url, QMap<QString, QString> textForm)
{
    QByteArray formData;
    QMap<QString,QString>::iterator it = textForm.begin();
    while(it != textForm.end()){
        formData.append(it.key() + "=" + it.value().toUtf8().toPercentEncoding() + "&");
        it++;
    }

    qDebug() << url;
    QNetworkAccessManager net;
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, "application/x-www-form-urlencoded;charset=UTF-8");
    QNetworkReply *reply = net.post(request, formData);

    // 添加消息循环机制...
    QEventLoop eventloop;
    connect(reply, SIGNAL(finished()), &eventloop, SLOT(quit()));
    QTimer::singleShot(5000, &eventloop, &QEventLoop::quit);
    qDebug() << "timer started";
    eventloop.exec();
    qDebug() << "eventLoop executed";

    QByteArray array;
    if(reply->isFinished()){
        if(reply->error() == QNetworkReply::NoError){
            qDebug() << "success";
        }
        array.append(reply->readAll());
    }
    else{
        disconnect(reply, &QNetworkReply::finished, &eventloop, &QEventLoop::quit);
        reply->abort();
        qDebug() << "timeout";
    }
    reply->deleteLater();

    QString responose = QString::fromUtf8(array);
    // qDebug() << responose;
    return responose;
}

QString HttpUtil::getQeuryParam(const QUrl &url, const QString param)
{
    QString query = url.query();
    QRegExp reg(QString(".*%1=([^&]+)&?.*").arg(param));
    if(reg.exactMatch(query)){
        return QUrl::fromPercentEncoding(reg.cap(1).toUtf8());
    }
    else{
        return QString::null;
    }
}
